package pwd.allen.androiddemo.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.transition.Slide;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.ScrollView;

import pwd.allen.androiddemo.R;
import pwd.allen.androiddemo.util.MethodCommon;

public class PopWindowActivity extends AppCompatActivity implements View.OnClickListener {

    private Button button;
    private PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pop_window);
        button = findViewById(R.id.button);
        button.setOnClickListener(this);

        // 创建popupwindow里的视图
        View popupView = getLayoutInflater().inflate(R.layout.fragment_dynamic, null);

        //<editor-fold desc="在不改xml的前提下给fragment外套个垂直滚动的，懒得另外写个xml">
        ScrollView scrollView = new ScrollView(this);
        scrollView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        scrollView.addView(popupView);
        //</editor-fold>

        // focusable设为true能实现点击外部区域关闭popupwindow
        popupWindow = new PopupWindow(scrollView, ViewGroup.LayoutParams.MATCH_PARENT, MethodCommon.dip2px(this, 300), true);
        // 设置背景
        ColorDrawable dw = new ColorDrawable(getResources().getColor(R.color.orange, null));
        popupWindow.setBackgroundDrawable(dw);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Slide slide = new Slide();
            slide.setDuration(300);
            slide.setSlideEdge(Gravity.LEFT);
            // 设置进场动画 从左边滑入
            popupWindow.setEnterTransition(slide);
            // 设置离场动画
            popupWindow.setExitTransition(slide);
        }

        popupView.findViewById(R.id.tv_desc).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                // 相对于指定的控件下方展示
                popupWindow.showAsDropDown(button, 0, 0);
                break;
            case R.id.tv_desc:
                // 关闭
                popupWindow.dismiss();
                break;
        }

    }
}
